package com.czk.model.responsebilitychain.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 对象链连起来（初始化）&& 使用
 * 相当于在service层，不过进行了封装
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/27 22:20
 */
@Component
public class HandlerInitialize {
    /**
     * 注入对象集合
     */
    @Autowired
    private List<AbstractHandler> list;
    private AbstractHandler abstractHandler;

    /**
     * spring注入后自动执行，责任链的对象连接起来
     */
    @PostConstruct
    public void initializeChainFilter() {
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                // 第一个，设置下一个
                abstractHandler = list.get(i);
            } else {
                AbstractHandler currentHandler = list.get(i - 1);
                AbstractHandler nextHandler = list.get(i);
                // 设置
                currentHandler.setNextHandler(nextHandler);
            }
        }
    }

    /**
     * 校验
     *
     * @param request
     * @param response
     */
    public void check(HttpServletRequest request, HttpServletResponse response) {
        // 参数非空校验
        // 安全校验
        // 黑名单校验
        // 规则校验
        abstractHandler.filter(request, response);
    }
}
